package com.example.saiaadmin.hander;

import com.example.saiaadmin.utils.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * security匿名未登录的时候访问，遇到需要登录认证的时候被调用
 */
@Component
public class AnonymousNotLoggedInAuthentication implements AuthenticationEntryPoint {

    private static final Logger log = LoggerFactory.getLogger(AnonymousNotLoggedInAuthentication.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("权限错误");
        response.setStatus(401);
        // 设置响应内容类型为JSON
        response.setContentType("application/json");
        // 设置字符编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        // 获取response的writer对象
        PrintWriter out = response.getWriter();
        String value = new ObjectMapper().writeValueAsString( ResultData.error("无权限"));
        // 将JSON数据写入响应中
        out.write(value);
        // 清空缓冲区，发送数据
        out.flush();
        out.close();
    }
}
